package com.im.service.fixAsset.smo;

import com.im.MDA;
import com.im.service.dto.BaseException;
import com.im.service.dto.FixAsset;
import com.im.service.dto.FundSource;
import com.im.service.dto.PlanDeclareSet;
import com.im.service.dto.Staff;
import com.im.service.fixAsset.dao.IFixAssetOperDao;
import com.im.service.fundPlan.dao.IFundPlanQueryDAO;
import com.im.service.investPlan.dao.IInvestPlanOperDAO;
import com.im.service.projectInfo.dao.IFundSourceOperDAO;
import com.im.service.projectInfo.dao.IFundSourceQueryDAO;
import com.im.util.DateUtil;
import com.im.util.JsonUtil;
import com.im.util.ListUtil;
import com.im.util.ReturnsUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class IFixAssetOperSmoImpl implements IFixAssetOperSmo {

    private static final Logger logger = LogManager.getLogger(IFixAssetOperSmoImpl.class);

    @Autowired
    private IFixAssetOperDao fixAssetOperDao;
    @Autowired
    private IFundSourceOperDAO fundSourceOperDAO;
    @Autowired
    private IFundSourceQueryDAO fundSourceQueryDAO;

    @Override
    public String addFixAsset(String jsonStr, Staff staff) throws Exception{
        try {
            // 1.json格式校验
            if (!JsonUtil.jsonValidate(jsonStr)) {
                throw new BaseException(
                        new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
            }
            JSONObject jsonObj = JSONObject.fromObject(jsonStr);
            String errorMsg = "获取新增固定资产申报设置入参时：";
            // 2.获取入参 固定资产申报信息
            String fixAssetName  = JsonUtil.getStringFromJSON(jsonObj, "fixAssetName", errorMsg);
            String fixAssetCode  = JsonUtil.getStringFromJSON(jsonObj, "fixAssetCode", errorMsg);
            String impleProjId  = JsonUtil.getStringFromJSON(jsonObj, "impleProjId", errorMsg);
            String declareSetId  = JsonUtil.getStringFromJSON(jsonObj, "declareSetId", errorMsg);
            String yearDt = JsonUtil.getStringFromJSON(jsonObj, "yearDt", errorMsg);
            String applicant = JsonUtil.getStringFromJSON(jsonObj, "applicant", errorMsg);
            String statusCd = JsonUtil.getStringFromJSON(jsonObj, "statusCd", errorMsg);
            String docCode = JsonUtil.getStringFromJSON(jsonObj, "docCode", errorMsg);
            Integer total = JsonUtil.getIntegerFromJSON(jsonObj, "total", errorMsg);
            String enterDt = JsonUtil.getStringFromJSON(jsonObj, "enterDt", errorMsg);
            String endDt = JsonUtil.getStringFromJSON(jsonObj, "endDt", errorMsg);
            String examineDescription = JsonUtil.getStringFromJSON(jsonObj, "examineDescription", errorMsg);
            String description = JsonUtil.getStringFromJSON(jsonObj, "description", errorMsg);

            FixAsset fixAsset = new FixAsset();
            String fixAssetId = UUID.randomUUID().toString();
            fixAsset.setFixAssetId(fixAssetId);
            fixAsset.setFixAssetName(fixAssetName);
            fixAsset.setFixAssetCode(fixAssetCode);
            fixAsset.setImpleProjId(impleProjId);
            fixAsset.setDeclareSetId(declareSetId);
            fixAsset.setYearDt(yearDt);
            fixAsset.setApplicant(applicant);
            if(null==statusCd){
                fixAsset.setStatusCd("10");
            }else{
                fixAsset.setStatusCd(statusCd);
            }
            fixAsset.setDocCode(docCode);
            fixAsset.setTotal(total);
            fixAsset.setEnterDt(enterDt);
            fixAsset.setEndDt(endDt);
            fixAsset.setExamineDescription(examineDescription);
            fixAsset.setDescription(description);

            fixAssetOperDao.addFixAsset(fixAsset);
			// 5.新增资金信息
			FundSource fundSource = new FundSource();
			fundSource.setFundSourceObjType(MDA.FUND_SOURCE_OBJ_TYPE_FUND_501);// 投资计划
			fundSource.setFundSourceObj(fixAssetId);
			fundSource.setStatusCd(Integer.parseInt(MDA.EFFECT_STATUS_CD));
			fundSource.setYearDt(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_B));// TODO
																					// 年度如何定
			Double fundSourceBu = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceBu", errorMsg);
            Double fundSourceSheng = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceSheng", errorMsg);
            Double fundSourceGao = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceGao", errorMsg);
            Double fundSourceQi = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceQi", errorMsg);
            Double fundSourceShi = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceShi", errorMsg);
			// 部补助
			if (fundSourceBu != null) {
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_BU);
				fundSource.setFundVal(String.valueOf(fundSourceBu));
				fundSourceOperDAO.addFundSource(fundSource);
			}
			// 省财政
			if (fundSourceSheng != null) {
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_SHENG);
				fundSource.setFundVal(String.valueOf(fundSourceSheng));
				fundSourceOperDAO.addFundSource(fundSource);
			}
			// 高速水运融资
			if (fundSourceGao != null) {
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_GAO);
				fundSource.setFundVal(String.valueOf(fundSourceGao));
				fundSourceOperDAO.addFundSource(fundSource);
			}
			// 市州配套
			if (fundSourceShi != null) {
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_SHI);
				fundSource.setFundVal(String.valueOf(fundSourceShi));
				fundSourceOperDAO.addFundSource(fundSource);
			}
			// 企业自筹
			if (fundSourceQi != null) {
				fundSource.setFundSourceId(UUID.randomUUID().toString());
				fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_QI);
				fundSource.setFundVal(String.valueOf(fundSourceQi));
				fundSourceOperDAO.addFundSource(fundSource);
			}
            return ReturnsUtil.returnSuccess(new JSONObject()).toString();
        } catch (BaseException e) {
            if (logger.isErrorEnabled()) {
                logger.error(ReturnsUtil.getStackTrackMessage(e));
            }
            return ReturnsUtil.returnFailure(e.toString());
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error(ReturnsUtil.getStackTrackMessage(e));
            }
            return ReturnsUtil.returnFailure(e.toString());
        }
    }

    @Override
    public String updateFixAsset(String jsonStr, Staff staff) throws Exception{
        try {
            // 1.json格式校验
            if (!JsonUtil.jsonValidate(jsonStr)) {
                throw new BaseException(
                        new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
            }
            JSONObject jsonObj = JSONObject.fromObject(jsonStr);
            String errorMsg = "获取新增固定资产申报设置入参时：";
            // 2.获取入参 固定资产申报信息
            String fixAssetId = JsonUtil.getStringFromJSON(jsonObj, "fixAssetId", errorMsg);
            String fixAssetName  = JsonUtil.getStringFromJSON(jsonObj, "fixAssetName", errorMsg);
            String fixAssetCode  = JsonUtil.getStringFromJSON(jsonObj, "fixAssetCode", errorMsg);
            String impleProjId  = JsonUtil.getStringFromJSON(jsonObj, "impleProjId", errorMsg);
            String declareSetId  = JsonUtil.getStringFromJSON(jsonObj, "declareSetId", errorMsg);
            String yearDt = JsonUtil.getStringFromJSON(jsonObj, "yearDt", errorMsg);
            String applicant = JsonUtil.getStringFromJSON(jsonObj, "applicant", errorMsg);
            String statusCd = JsonUtil.getStringFromJSON(jsonObj, "statusCd", errorMsg);
            String docCode = JsonUtil.getStringFromJSON(jsonObj, "docCode", errorMsg);
            Integer total = JsonUtil.getIntegerFromJSON(jsonObj, "total", errorMsg);
            String enterDt = JsonUtil.getStringFromJSON(jsonObj, "enterDt", errorMsg);
            String endDt = JsonUtil.getStringFromJSON(jsonObj, "endDt", errorMsg);
            String examineDescription = JsonUtil.getStringFromJSON(jsonObj, "examineDescription", errorMsg);
            String description = JsonUtil.getStringFromJSON(jsonObj, "description", errorMsg);

            FixAsset fixAsset = new FixAsset();
            fixAsset.setFixAssetId(fixAssetId);
            fixAsset.setFixAssetName(fixAssetName);
            fixAsset.setFixAssetCode(fixAssetCode);
            fixAsset.setImpleProjId(impleProjId);
            fixAsset.setDeclareSetId(declareSetId);
            fixAsset.setYearDt(yearDt);
            fixAsset.setApplicant(applicant);
            if(null==statusCd){
                fixAsset.setStatusCd("10");
            }else{
                fixAsset.setStatusCd(statusCd);
            }
            fixAsset.setDocCode(docCode);
            fixAsset.setTotal(total);
            fixAsset.setEnterDt(enterDt);
            fixAsset.setEndDt(endDt);
            fixAsset.setExamineDescription(examineDescription);
            fixAsset.setDescription(description);

            fixAssetOperDao.updateFixAsset(fixAsset);

            // 5.新增资金信息
            FundSource fundSource = new FundSource();
            fundSource.setFundSourceObjType(MDA.FUND_SOURCE_OBJ_TYPE_FUND_501);// 投资计划
            fundSource.setFundSourceObj(fixAssetId);
            fundSource.setStatusCd(Integer.parseInt(MDA.EFFECT_STATUS_CD));
            fundSource.setYearDt(DateUtil.getNow(DateUtil.DATE_FORMATE_STRING_B));// TODO
            // 年度如何定
            Double fundSourceBu = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceBu", errorMsg);
            Double fundSourceSheng = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceSheng", errorMsg);
            Double fundSourceGao = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceGao", errorMsg);
            Double fundSourceQi = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceQi", errorMsg);
            Double fundSourceShi = JsonUtil.getDoubleFromJSON(jsonObj, "fundSourceShi", errorMsg);
            // 部补助
            if (fundSourceBu != null) {
                fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_BU);
                List<FundSource> fundSources = fundSourceQueryDAO.queryFoundSource(fundSource);
                fundSource.setFundVal(String.valueOf(fundSourceBu));
                if(!ListUtil.isListEmpty(fundSources)){
                    fundSource.setFundSourceId(fundSources.get(0).getFundSourceId());
                    fundSourceOperDAO.updateFundSource(fundSource);
                }else{
                    fundSource.setFundSourceId(UUID.randomUUID().toString());
                    fundSourceOperDAO.addFundSource(fundSource);
                }
            }

            // 省财政
            if (fundSourceSheng != null) {
                fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_SHENG);
                List<FundSource> fundSources = fundSourceQueryDAO.queryFoundSource(fundSource);
                fundSource.setFundVal(String.valueOf(fundSourceSheng));
                if(!ListUtil.isListEmpty(fundSources)){
                    fundSource.setFundSourceId(fundSources.get(0).getFundSourceId());
                    fundSourceOperDAO.updateFundSource(fundSource);
                }else{
                    fundSource.setFundSourceId(UUID.randomUUID().toString());
                    fundSourceOperDAO.addFundSource(fundSource);
                }
            }

            // 高速水运融资
            if (fundSourceGao != null) {
                fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_GAO);
                List<FundSource> fundSources = fundSourceQueryDAO.queryFoundSource(fundSource);
                fundSource.setFundVal(String.valueOf(fundSourceGao));
                if(!ListUtil.isListEmpty(fundSources)){
                    fundSource.setFundSourceId(fundSources.get(0).getFundSourceId());
                    fundSourceOperDAO.updateFundSource(fundSource);
                }else{
                    fundSource.setFundSourceId(UUID.randomUUID().toString());
                    fundSourceOperDAO.addFundSource(fundSource);
                }
            }

            // 市州配套
            if (fundSourceShi != null) {
                fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_SHI);
                List<FundSource> fundSources = fundSourceQueryDAO.queryFoundSource(fundSource);
                fundSource.setFundVal(String.valueOf(fundSourceShi));
                if(!ListUtil.isListEmpty(fundSources)){
                    fundSource.setFundSourceId(fundSources.get(0).getFundSourceId());
                    fundSourceOperDAO.updateFundSource(fundSource);
                }else{
                    fundSource.setFundSourceId(UUID.randomUUID().toString());
                    fundSourceOperDAO.addFundSource(fundSource);
                }
            }

            // 企业自筹
            if (fundSourceQi != null) {
                fundSource.setFundSourceType(MDA.FUND_SOURCE_TYPE_QI);
                List<FundSource> fundSources = fundSourceQueryDAO.queryFoundSource(fundSource);
                fundSource.setFundVal(String.valueOf(fundSourceQi));
                if(!ListUtil.isListEmpty(fundSources)){
                    fundSource.setFundSourceId(fundSources.get(0).getFundSourceId());
                    fundSourceOperDAO.updateFundSource(fundSource);
                }else{
                    fundSource.setFundSourceId(UUID.randomUUID().toString());
                    fundSourceOperDAO.addFundSource(fundSource);
                }
            }
            return ReturnsUtil.returnSuccess(new JSONObject()).toString();
        } catch (BaseException e) {
            if (logger.isErrorEnabled()) {
                logger.error(ReturnsUtil.getStackTrackMessage(e));
            }
            return ReturnsUtil.returnFailure(e.toString());
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error(ReturnsUtil.getStackTrackMessage(e));
            }
            return ReturnsUtil.returnFailure(e.toString());
        }
    }

    @Override
    public String updateFixAssetStatus(String jsonStr, Staff staff) throws Exception{
        try {
            // 1.json格式校验
            if (!JsonUtil.jsonValidate(jsonStr)) {
                throw new BaseException(
                        new StringBuffer().append("字符串： ").append(jsonStr).append("不符合JSON格式").toString());
            }
            JSONObject jsonObj = JSONObject.fromObject(jsonStr);
            String errorMsg = "获取新增固定资产申报设置入参时：";
            // 2.获取入参 固定资产申报信息
            JSONArray fixAssetIdJson = jsonObj.getJSONArray("fixAssetIds");
            for(int i=0;i<fixAssetIdJson.size();i++){
                String fixAssetId = fixAssetIdJson.getString(i);
                FixAsset fixAsset = new FixAsset();
                fixAsset.setFixAssetId(fixAssetId);
                fixAsset.setStatusCd("20");
                fixAssetOperDao.updateFixAsset(fixAsset);
            }

            return ReturnsUtil.returnSuccess(new JSONObject()).toString();
        } catch (BaseException e) {
            if (logger.isErrorEnabled()) {
                logger.error(ReturnsUtil.getStackTrackMessage(e));
            }
            return ReturnsUtil.returnFailure(e.toString());
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error(ReturnsUtil.getStackTrackMessage(e));
            }
            return ReturnsUtil.returnFailure(e.toString());
        }
    }


}
